// index.js
const app = getApp()
const api = require('../../api/api')
const util = require('../../utils/js/util')
Page({
  data: {
    safeToBottom: util.getSafeToBottom(),
    process: 1,
    region: [], // 省市区数据
    username: '', // 姓名
    sex: '0', // 1 男 0 女
    marriage: '0', // 1 已婚 0 未婚
    phone: '', // 手机号
    birthday: util.getDateTime().format('Y-M-D'), // 出生年月日

    salary: [], // 薪资范围选项
    salaryActive: '0', // 选中薪资

    payment: [{ title: '不限', value: '0' }, { title: '日结', value: '1' }, { title: '月结', value: '2' }], // 支付方式选项
    paymentActive: '0', // 支付方式选中

    workStatus: '1', // 0 待业 1 在职

    goalJobValueRange: [], // 可选所有岗位
    goalJobValueSelected: [], // 选中岗位
    goalJobValue: '', // 选中岗位字符串

    workRegionValueRange: [], // 可选期望工作区域
    workRegionValueSelected: [], // 选中期望工作区域
    workRegionValue: '', // 选中期望工作区域字符串

    skillValueRange: [], // 可选技能
    skillValueSelected: [], // 选中技能
    skillValue: '', // 选中技能字符串

    cleanroom: 0, // 无尘服 0 接受 1 不接受

    workedValueRange: [], // 从事过行业
    workedValueSelected: [], // 从事过行业
    workedValue: '', // 从事过行业

    front: '', // 身份证正面
    back: '', // 身份证反面

    qrcode: '', // 客服二维码
    pop: {
      show: false,
      type: '' // goalJobs 目标岗位 workRegion 期望工作区域 skills 技能 workeds 从事过的行业
    }
  },
  async onLoad() {
    await this.getConfigList();
    this.render1();
    this.getkfqrcode();
  },
  // 填写结束，弹窗关闭
  afterleave() {
    if (this.data.pop.type == 'qrcode') {
      wx.reLaunch({ url: '../index/index' })
    }
  },
  // 获取客服二维码
  async getkfqrcode() {
    const res = await api.getCodeConfig()
    this.setData({ qrcode: res.qrcode1 })
  },
  // 简历回渲染
  render1() {
    const { userInfo } = app.globalData
    if (userInfo.post) {
      const post = userInfo.post.split(',')
      const goalJobValueRange = this.data.goalJobValueRange.map(v => ({ ...v, children: v.children.map(v1 => ({ ...v1, selected: post.includes(v1.key) })) }))
      let goalJobValueSelected = []
      goalJobValueRange.forEach(v => goalJobValueSelected = goalJobValueSelected.concat(v.children.filter(v1 => v1.selected)))
      this.setData({
        goalJobValueRange,
        goalJobValueSelected,
        goalJobValue: goalJobValueSelected.map(v => v.value).join(','),
      })
    }
    if (userInfo.workarea) {
      const workarea = userInfo.workarea.split(',')
      const workRegionValueRange = this.data.workRegionValueRange.map(v => ({ ...v, children: v.children.map(v1 => ({ ...v1, selected: workarea.includes(v1.key) })) }))
      let workRegionValueSelected = []
      workRegionValueRange.forEach(v => workRegionValueSelected = workRegionValueSelected.concat(v.children.filter(v1 => v1.selected)))
      this.setData({
        workRegionValueRange,
        workRegionValueSelected,
        workRegionValue: workRegionValueSelected.map(v => v.value).join(','),
      })
    }
    if (userInfo.skill) {
      const skill = userInfo.skill.split(',')
      const skillValueRange = this.data.skillValueRange.map(v => { skill.includes(v.key) && (v.selected = true); return v })
      const skillValueSelected = skillValueRange.filter(v => v.selected)
      this.setData({
        skillValueRange,
        skillValueSelected,
        skillValue: skillValueSelected.map(v => v.value).join(','),
      })
    }
    if (userInfo.industry) {
      const industry = userInfo.industry.split(',')
      const workedValueRange = this.data.workedValueRange.map(v => { industry.includes(v.key) && (v.selected = true); return v })
      const workedValueSelected = workedValueRange.filter(v => v.selected)
      this.setData({
        workedValueRange,
        workedValueSelected,
        workedValue: workedValueSelected.map(v => v.value).join(','),
      })
    }
    userInfo.location && this.setData({ region: userInfo.location.split('/') })
    userInfo.nickname && this.setData({ username: userInfo.nickname })
    userInfo.birthday && this.setData({ birthday: userInfo.birthday })
    userInfo.gender && this.setData({ sex: userInfo.gender })
    userInfo.mobile && this.setData({ phone: userInfo.mobile })
    userInfo.ismarried && this.setData({ marriage: userInfo.ismarried })
    userInfo.salary && this.setData({ salaryActive: this.data.salary.findIndex(v => v.key == userInfo.salary) })
    userInfo.isonjob && this.setData({ workStatus: userInfo.isonjob })
    userInfo.front_idcard && this.setData({ front: userInfo.front_idcard })
    userInfo.back_idcard && this.setData({ back: userInfo.back_idcard })
    this.setData({ paymentActive: this.data.payment.findIndex(v => v.value == userInfo.salarytype), cleanroom: userInfo.undust })
  },
  // 获取简历配置项
  async getConfigList() {
    const res = await api.getConfigList()
    Object.keys(res).forEach(v => res[v] = Object.entries(res[v]).map(([key, value]) => ({ key, value, selected: false })))
    for (const i in res.posttype) {
      res.posttype[i].children = []
      for (const j in res.post) {
        res.post[j].selected = false
        res.post[j].key.split('.')[0] == res.posttype[i].key && res.posttype[i].children.push(res.post[j])
      }
    }
    for (const i in res.workcity) {
      res.workcity[i].children = []
      for (const j in res.workarea) {
        res.workarea[j].selected = false
        res.workarea[j].key.split('.')[0] == res.workcity[i].key && res.workcity[i].children.push(res.workarea[j])
      }
    }
    this.setData({
      salary: res.salary,
      goalJobValueRange: res.posttype,
      workRegionValueRange: res.workcity,
      skillValueRange: res.skill,
      workedValueRange: res.industry,
    })
    console.log(this.data.workRegionValueRange)
  },
  // 多选选择
  check({ currentTarget: { dataset: { type: { type, index, pindex } } } }) {
    if (type == 'goalJobValueRange') {
      this.setData({ [`goalJobValueRange[${pindex}].children[${index}].selected`]: !this.data.goalJobValueRange[pindex].children[index].selected })
    }
    if (type == 'workRegion') {
      this.setData({ [`workRegionValueRange[${pindex}].children[${index}].selected`]: !this.data.workRegionValueRange[pindex].children[index].selected })
    }
    if (type == 'skills') {
      this.setData({ [`skillValueRange[${index}].selected`]: !this.data.skillValueRange[index].selected })
    }
    if (type == 'workeds') {
      this.setData({ [`workedValueRange[${index}].selected`]: !this.data.workedValueRange[index].selected })
    }
  },
  // 多选确定
  confirm({ currentTarget: { dataset: { type } } }) {
    if (type == 'goalJobs') {
      const { goalJobValueRange } = this.data
      let selectedJobs = []
      goalJobValueRange.forEach(v => selectedJobs = selectedJobs.concat(v.children.filter(v1 => v1.selected)))
      this.setData({ goalJobValue: selectedJobs.map(v => v.value).join(','), goalJobValueSelected: selectedJobs })
    }
    if (type == 'workRegion') {
      const { workRegionValueRange } = this.data
      let selectedWorkRegion = []
      workRegionValueRange.forEach(v => selectedWorkRegion = selectedWorkRegion.concat(v.children.filter(v1 => v1.selected)))
      this.setData({ workRegionValue: selectedWorkRegion.map(v => v.value).join(','), workRegionValueSelected: selectedWorkRegion })
    }
    if (type == 'skills') {
      const { skillValueRange } = this.data
      let selectedskills = skillValueRange.filter(v => v.selected)
      this.setData({ skillValue: selectedskills.map(v => v.value).join(','), skillValueSelected: selectedskills })
    }
    if (type == 'workeds') {
      const { workedValueRange } = this.data
      let selectedworkeds = workedValueRange.filter(v => v.selected)
      this.setData({ workedValue: selectedworkeds.map(v => v.value).join(','), workedValueSelected: selectedworkeds })
    }
    this.setData({ 'pop.show': false })
  },
  // 获取手机号
  async getphonenumber(e) {
    const res = await api.getMobile({ code: e.detail.code })
    this.setData({ phone: res })
  },
  // 性别改变
  sexChange({ detail: { value } }) {
    this.setData({ sex: value })
  },
  // 婚姻改变
  marriageChange({ detail: { value } }) {
    this.setData({ marriage: value })
  },
  // 生日改变
  birthdayChange({ detail: { value } }) {
    this.setData({ birthday: value })
  },
  // 地区改变
  regionChange({ detail: { value } }) {
    this.setData({ region: value })
  },
  // 下一步
  next() {
    const { process } = this.data
    if (process == 1) {
      const { region, phone, address } = this.data
      if (!phone) return util.toast('请填写手机号')
      if (region.length == 0) return util.toast('请选择当前所在地')
      this.setData({ process: this.data.process + 1 })
    }
    if (process == 2) {
      const { goalJobValueSelected, workRegionValueSelected } = this.data
      if (goalJobValueSelected.length == 0) return util.toast('请选择期望岗位')
      if (workRegionValueSelected.length == 0) return util.toast('请选择期望工作区域')
      this.setData({ process: this.data.process + 1 })
    }
    if (process == 3) {
      const { workedValueSelected } = this.data
      if (workedValueSelected.length == 0) return util.toast('请选择从事过的行业')
      this.setData({ process: this.data.process + 1 })
    }
  },
  // 上一步
  prev() {
    this.setData({ process: this.data.process - 1 })
  },
  // 提交简历信息
  submit() {
    wx.showModal({
      content: '确定提交简历信息',
      complete: async ({ cancel, confirm }) => {
        if (cancel) return
        if (confirm) {
          console.log(app.globalData.userInfo?.token);

          if (!app.globalData.userInfo?.token) {
            const data = { code: await util.login(), type: 'register' }
            app.globalData.inviteUserId && (data.inviteUserId = app.globalData.inviteUserId)
            app.globalData.userInfo = await api.login(data)
          }
          await api.profile({
            'ext.undust': this.data.cleanroom,
            'ext.salarytype': this.data.payment[this.data.paymentActive].value,
            'nickname': this.data.username,
            'gender': this.data.sex + '',
            'birthday': this.data.birthday,
            'mobile': this.data.phone,
            'ext.ismarried': this.data.marriage,
            'ext.location': this.data.region.join('/'),
            'ext.address': this.data.address,
            'ext.skill': this.data.skillValueSelected.map(v => v.key).join(','),
            'ext.industry': this.data.workedValueSelected.map(v => v.key).join(','),
            'ext.post': this.data.goalJobValueSelected.map(v => v.key).join(','),
            'ext.isonjob': this.data.workStatus,
            'ext.salary': this.data.salary[this.data.salaryActive].key,
            'ext.workarea': this.data.workRegionValueSelected.map(v => v.key).join(','),
            'ext.front_idcard': this.data.front,
            'ext.back_idcard': this.data.back,
          })
          util.toast('简历提交成功')
          this.setData({ pop: { type: 'qrcode', show: true } })
        }
      }
    })
  },
  // 上传图片
  upimg({ currentTarget: { dataset: { type } } }) {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: async res => {
        wx.uploadFile({
          url: "https://szb.demo-dev.cn/api/common/upload",
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          header: { "token": app.globalData.userInfo?.token || '' },
          success: res1 => {
            if (res1.statusCode === 200 && res1.errMsg === "uploadFile:ok") {
              const res2 = JSON.parse(res1.data)
              if (res2.code === 1) {
                util.toast(res2.msg)
                this.setData({ [type]: res2.data.fullurl })
              } else {
                util.toast(res2.msg)
              }
            } else {
              util.toast('上传失败，网络错误')
            }
          }
        })
      }
    })
  },
  // 跳转详情
  gotoDetail({ currentTarget: { dataset: { type } } }) {
    wx.navigateTo({ url: '../article/index?id=' + type })
  },
  // 目标岗位
  goalJobs() {
    this.setData({ pop: { type: 'goalJobs', show: true } })
  },
  // 期望工作区域
  workRegion() {
    this.setData({ pop: { type: 'workRegion', show: true } })
  },
  // 支付方式改变
  paymentChange({ detail: { value } }) {
    this.setData({ paymentActive: value })
  },
  // 技能
  skills() {
    this.setData({ pop: { type: 'skills', show: true } })
  },
  // 接受/不接受无尘服
  cleanroomChange({ detail: { value } }) {
    this.setData({ cleanroom: value })
  },
  // 从事过的行业
  workeds() {
    this.setData({ pop: { type: 'workeds', show: true } })
  },
  // 期望薪资改变
  salaryChange({ detail: { value } }) {
    this.setData({ salaryActive: value })
  },
  // 在职状态改变
  workStatusChange({ detail: { value } }) {
    this.setData({ workStatus: value })
  },
});